package com.qdsgjsfk.vision.ui;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.qdsgjsfk.vision.R;
import com.qdsgjsfk.vision.base.BaseActivity;
import com.qdsgjsfk.vision.base.BaseApplication;
import com.qdsgjsfk.vision.eventbus.BlueTooth;
import com.qdsgjsfk.vision.eventbus.Logout;
import com.qdsgjsfk.vision.ui.dialog.LogoutDialog;
import com.qdsgjsfk.vision.ui.dialog.ScanDialog;
import com.qdsgjsfk.vision.ui.dialog.UpdateDialog;
import com.qdsgjsfk.vision.util.BitmapUtil;
import com.qdsgjsfk.vision.util.KeyCodeUtil;
import com.qdsgjsfk.vision.util.NetUtil;
import com.qdsgjsfk.vision.util.QrConfigUtil;
import com.qdsgjsfk.vision.util.ToastUtil;
import com.qdsgjsfk.vision.util.ToastUtils;
import com.qdsgjsfk.vision.util.UriUtils;
import com.qdsgjsfk.vision.util.UtilString;
import com.rest.business.RestProxy;
import com.rest.client.SSLAgent;
import com.rest.client.SSLSocketClient;
import com.rest.response.AxisResponse;
import com.rest.response.CompareFaceResponse;
import com.rest.response.QualifiedResponse;
import com.rest.response.TaskListResponse;
import com.rest.response.VersionResponse;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;
import cn.bertsir.zbar.QrConfig;
import cn.bertsir.zbar.QrManager;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import jz.joyoung.robot.util.LogUtil;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import util.PreferencesHelper;

/**
 * Created by HP on 2018/11/12.
 */

public class TypeActivity extends BaseActivity {

    //原图像 URI
    private Uri imgUriOri;
    //原图像 路径
    private String imgPathOri;

    public static int REQUEST_CODE_SCAN = 1;

    public static int REQUEST_CODE_FACE = 2;


    public static int REQUEST_GALLERY = 3;

    public static int REQUEST_CODE_SCAN_IP = 4;

    public static int REQUEST_CODE_TASK = 5;
    public static int REQUEST_CODE_TASK_CLASS = 6;

    @BindView(R.id.btn_zxing)
    ImageView btn_zxing;

    @BindView(R.id.btn_class)
    ImageView btn_class;

    @BindView(R.id.icon_switch_mission)
    ImageView icon_switch_mission;

    @BindView(R.id.tv_switch)
    TextView tv_switch;

    @BindView(R.id.face_search_container)
    LinearLayout face_search_container;

    @BindView(R.id.face_add_container)
    LinearLayout face_add_container;

    @BindView(R.id.tv_mission_name)
    TextView tv_mission_name;
    private long firstTime = 0;
    private LogoutDialog mLogoutDialog;
    private String currentTaskId, currentSchoolName;
    private ScanDialog mScanDialog;
    private UpdateDialog mUpdateDialog;
    private static final String TAG = "TypeActivity";

    @Override
    protected void initViews() {
        checkPermission();
        icon_switch_mission.setVisibility( View.INVISIBLE );
        PreferencesHelper.getInstance().set( this, "ipv4", "" );
        LogUtil.e( "权限" + BaseApplication.faceAdd + "       " + BaseApplication.faceSearch );
//        stopService( new Intent( this, SocketService.class ) );
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//            startForegroundService( new Intent( this, SocketService.class ) );
//        } else {
//            startService( new Intent( this, SocketService.class ) );
//        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!BaseApplication.faceSearch) {
            face_search_container.setVisibility( View.GONE );
        }
        if (!BaseApplication.faceAdd) {
            face_add_container.setVisibility( View.GONE );
        }
    }

    @Override
    protected void initData() {
        EventBus.getDefault().register( this );
        getTaskList( true );
//        getVersion();
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_type;
    }

    /**
     * 选择班级
     *
     * @time 2020/12/15 10:58
     */
    @OnClick(R.id.btn_class)
    void btn_class() {
        if (TextUtils.isEmpty( currentTaskId )) {
            Bundle bundle = new Bundle();
            bundle.putString( "title", "请先选择任务" );
            startActivityForResult( TaskListActivity.class, bundle, REQUEST_CODE_TASK_CLASS );
            return;
        }
        Bundle bundle = new Bundle();
        bundle.putString( "taskId", currentTaskId );
        startActivity( ClassActivity.class, bundle );
    }

    @OnClick(R.id.btn_zxing)
    void btn_zxing() {
        //先判断有无任务
//        getTaskList( false );
        startScan();
    }


    protected File createOriImageFile() throws IOException {
//        String imgNameOri = "HomePic_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imgNameOri = "aaa";

        File pictureDirOri = new File( Objects.requireNonNull( this.getExternalFilesDir( Environment.DIRECTORY_PICTURES ) ).getAbsolutePath() + "/OriPicture" );
        if (!pictureDirOri.exists()) {
            pictureDirOri.mkdirs();
        }
        File image = File.createTempFile(
                imgNameOri,         /* prefix */
                ".jpg",             /* suffix */
                pictureDirOri       /* directory */
        );
        imgPathOri = image.getAbsolutePath();
        return image;
    }


    @OnClick(R.id.btn_connect_device)
    void btn_connect_device() {
//        startActivity( DeviceActivity.class );
        startActivity( DeviceTypeActivity.class );
        BaseApplication.lastActivity = 0;
    }

//    @OnClick(R.id.btn_bluetooth)
//    void btn_bluetooth() {
//        stopService(new Intent(TypeActivity.this, BluetoothLeService.class));
//        stopService(new Intent(TypeActivity.this, BlueToothService.class));
//        startActivity(MyBlueTooth.class);
//    }
//
//    @OnClick(R.id.btn_ip)
//    void btn_ip() {
//        stopService(new Intent(TypeActivity.this, SocketService.class));
//        startService(new Intent(TypeActivity.this, SocketService.class));
//        Intent intent = new Intent(TypeActivity.this, CaptureActivity.class);
//        ZxingConfig config = new ZxingConfig();
//        config.setPlayBeep(true);//是否播放扫描声音 默认为true
//        config.setShake(true);//是否震动  默认为true
//        config.setDecodeBarCode(true);//是否扫描条形码 默认为true
//        config.setReactColor(R.color.mainColor);//设置扫描框四个角的颜色 默认为白色
////        config.setFrameLineColor(R.color.mainColor);//设置扫描框边框颜色 默认无色
//        config.setScanLineColor(R.color.mainColor);//设置扫描线的颜色 默认白色
//        config.setFullScreenScan(false);//是否全屏扫描  默认为true  设为false则只会在扫描框中扫描
//        intent.putExtra(Constant.INTENT_ZXING_CONFIG, config);
//        startActivityForResult(intent, REQUEST_CODE_SCAN_IP);
//        Toast.makeText(this, "请扫描视力表设备上的二维码", Toast.LENGTH_LONG).show();
//    }

    @OnClick(R.id.btn_userinfo)
    void btn_userinfo() {
        startActivity( UserActivity.class );
    }

//    @OnClick(R.id.btn_face)
//    void btn_face() {
//        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);// 打开相机
//        File oriPhotoFile = null;
//        try {
//            oriPhotoFile = createOriImageFile();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        if (oriPhotoFile != null) {
//            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
//                imgUriOri = Uri.fromFile(oriPhotoFile);
//            } else {
//                imgUriOri = FileProvider.getUriForFile(this, "com.qdsg.provider", oriPhotoFile);
//            }
//            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
//            intent.putExtra(MediaStore.EXTRA_OUTPUT, imgUriOri);
//            startActivityForResult(intent, REQUEST_CODE_FACE);
//        }


//        Intent intent = new Intent(
//                Intent.ACTION_PICK,
//                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//        intent.setType("image/*");
//        startActivityForResult(intent, REQUEST_GALLERY);
//    }


    @OnClick(R.id.btn_face_detector)
    void btn_face_detector() {
        if (TextUtils.isEmpty( currentTaskId )) {
            Bundle bundle = new Bundle();
            bundle.putString( "title", "请先选择任务" );
            startActivityForResult( TaskListActivity.class, bundle, REQUEST_CODE_TASK );
            return;
        }
        Bundle bundle = new Bundle();
        bundle.putInt( "faceType", 1 );//1  检索  2 上传
        bundle.putString( "taskId", currentTaskId );
        startActivity( FaceDetectorActivity.class, bundle );
    }

    @OnClick(R.id.btn_add_face)
    void btn_add_face() {
        if (TextUtils.isEmpty( currentTaskId )) {
            Bundle bundle = new Bundle();
            bundle.putString( "title", "请先选择任务" );
            startActivityForResult( TaskListActivity.class, bundle, REQUEST_CODE_TASK );
            return;
        }
        Bundle bundle = new Bundle();
        bundle.putString( "taskId", currentTaskId );
        startActivity( SelectTypeActivity.class, bundle );

    }

    @OnClick(R.id.btn_invite)
    void btn_invite() {
        if (TextUtils.isEmpty( currentTaskId )) {
            Bundle bundle = new Bundle();
            bundle.putString( "title", "请先选择任务" );
            startActivityForResult( TaskListActivity.class, bundle, REQUEST_CODE_TASK );
            return;
        }
        if (!BaseApplication.permission) {
            Toast.makeText( this, "您没有权限", Toast.LENGTH_SHORT ).show();
            return;
        }
        Bundle bundle = new Bundle();
        bundle.putString( "schoolName", currentSchoolName );
        bundle.putString( "taskId", currentTaskId );
        startActivity( InviteActivity.class, bundle );
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult( requestCode, resultCode, data );
        // 扫描二维码/条码回传
        //            if (data != null) {
        //                String content = data.getStringExtra( Constant.CODED_CONTENT );
        //                try {
        //                    scanQRCode( content, 0 );
        ////                    JSONObject obj = new JSONObject(content);
        ////                    getTaskWorker(obj.optString("taskId"), obj.optString("studentId"));
        //                } catch (Exception e) {
        //                    Toast.makeText( this, "二维码有误", Toast.LENGTH_SHORT ).show();
        //                }
        //
        //            }
        if (requestCode == REQUEST_CODE_FACE && resultCode == RESULT_OK) {

            compareFace( BitmapUtil.bitmaptoString( getImageThumbnail( imgPathOri ) ) );
        }

        if (requestCode == REQUEST_GALLERY && resultCode == RESULT_OK) {
            assert data != null;
            Uri imgUriSel = data.getData();
            String imgPathSel = UriUtils.formatUri( this, imgUriSel );
            compareFace( imgPathSel );
        }

        if (requestCode == REQUEST_CODE_TASK && resultCode == RESULT_OK) {
            tv_switch.setText( "切换任务" );
            icon_switch_mission.setVisibility( View.VISIBLE );
            assert data != null;
            currentSchoolName = data.getStringExtra( "schoolName" );
            tv_mission_name.setText( data.getStringExtra( "schoolName" ) );
            currentTaskId = data.getStringExtra( "taskId" );
        }
        if (requestCode == REQUEST_CODE_TASK_CLASS && resultCode == RESULT_OK) {
            tv_switch.setText( "切换任务" );
            icon_switch_mission.setVisibility( View.VISIBLE );
            currentSchoolName = data.getStringExtra( "schoolName" );
            tv_mission_name.setText( data.getStringExtra( "schoolName" ) );
            currentTaskId = data.getStringExtra( "taskId" );
            Bundle bundle = new Bundle();
            bundle.putString( "taskId", currentTaskId );
            startActivity( ClassActivity.class, bundle );
        }


    }


    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        KeyCodeUtil.keyCodeUp( keyCode );
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
            long secondTime = System.currentTimeMillis();
            if (secondTime - firstTime > 1000) {
                Toast.makeText( TypeActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT ).show();
                firstTime = secondTime;
                return true;
            } else {
                System.exit( 0 );
            }
        }
        return super.onKeyUp( keyCode, event );
    }


//    private void getTaskWorker(final String taskId, final String studentId) {
//        RestProxy.getInstance().getTaskWorkers(PreferencesHelper.getInstance().getString(this, "token"), taskId, new Observer<TaskWorkerResponse>() {
//            @Override
//            public void onSubscribe(Disposable d) {
//
//            }
//
//            @Override
//            public void onNext(TaskWorkerResponse taskWorkerResponse) {
//                for (String s : taskWorkerResponse.data.taskWorkerIds) {
//                    if (PreferencesHelper.getInstance().getString(TypeActivity.this, "userId").equals(s) || PreferencesHelper.getInstance().getInt(TypeActivity.this, "perm") == 1) {
//                        Intent intMain = new Intent(getApplicationContext(), StudentDetailActivity.class);
//                        Bundle bd = new Bundle();
//                        bd.putString("studentId", studentId);
//                        bd.putString("taskId", taskId);
//                        intMain.putExtras(bd);
//                        startActivity(intMain);
//                        return;
//                    }
//                }
//                Toast.makeText(TypeActivity.this, "权限不足", Toast.LENGTH_SHORT).show();
//    btn_connect_device//            }
//
//            @Override
//            public void onError(Throwable e) {
//                if (e instanceof ApiException) {
//                    Toast.makeText(TypeActivity.this, ((ApiException) e).errorMessage, Toast.LENGTH_SHORT).show();
//                } else {
//                    Toast.makeText(TypeActivity.this, "服务器异常", Toast.LENGTH_SHORT).show();
//                }
//            }
//
//            @Override
//            public void onComplete() {
//
//            }
//        });
//    }


    private void scanQRCode(String url) {//0 扫学生  1加人脸
        showProgressDialog( mContext );
        LogUtil.e( "scanQRCode==", url );
        OkHttpClient okHttpClient = new OkHttpClient.Builder().sslSocketFactory( SSLSocketClient.getSSLSocketFactory() )
                .hostnameVerifier( SSLSocketClient.getHostnameVerifier() )
                .build();
        final Request request = new Request.Builder()
                .url( url )
                .addHeader( "Authorization", PreferencesHelper.getInstance().getString( this, "token" ) )
                .get()//默认就是GET请求，可以不写
                .build();
        LogUtil.e( "scanQRCodetoken==", PreferencesHelper.getInstance().getString( this, "token" ) );
        Call call = okHttpClient.newCall( request );
        call.enqueue( new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                dismissProgressDialog();
                LogUtil.e( "扫描出错" + e.toString() );
                LogUtil.e( "扫描出错--" + e.getMessage() );
                ToastUtils.show( mContext, "加载失败，请检查网络" );
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                try {
                    dismissProgressDialog();
                    assert response.body() != null;
                    String s = response.body().string();
                    runOnUiThread( () -> LogUtil.e( "onResponse==", s ) );
                    JSONObject obj = new JSONObject( s );
                    int code = obj.getInt( "code" );
                    if (code == 600) {
                        showLogoutDialog();
                    } else {
                        try {
                            JSONObject json = new JSONObject( obj.optString( "data" ) );
                            int type = json.optInt( "type" );
                            LogUtil.e( "onResponse111==", type + "" );
                            if (type == 10) {
                                if (0 == 1) {
                                    String sid = json.optString( "sid" );
                                    Intent intMain = new Intent( getApplicationContext(), FaceDetectorActivity.class );
                                    Bundle bd = new Bundle();
                                    bd.putString( "studentId", sid );
                                    bd.putInt( "faceType", 0 );
                                    intMain.putExtras( bd );
                                    startActivity( intMain );
                                } else {
                                    String sid = json.optString( "sid" );
                                    if (UtilString.isEmpty( currentTaskId )) {
                                        runOnUiThread( () -> Toast.makeText( mContext, "您目前无任务,无法扫描学生二维码", Toast.LENGTH_SHORT ).show() );
                                    } else {
                                        Intent intMain;
                                        LogUtil.e( "配置其他项" + BaseApplication.isShowOther );
                                        if (BaseApplication.isShowAxis || BaseApplication.isShowOther) {
                                            intMain = new Intent( getApplicationContext(), StudentDetailOtherActivity.class );
                                        } else {
                                            intMain = new Intent( getApplicationContext(), StudentDetailActivity.class );
                                        }
                                        Bundle bd = new Bundle();
                                        bd.putString( "studentId", sid );
                                        bd.putString( "taskId", currentTaskId );
                                        intMain.putExtras( bd );
                                        startActivity( intMain );

                                    }
//                            String tid = json.optString("tid");
//                            if (!tid.equals(currentTaskId)) {
//                                runOnUiThread(new Runnable() {
//                                    @Override
//                                    public void run() {
//                                        if (TextUtils.isEmpty(currentTaskId)) {
//                                            Toast.makeText(TypeActivity.this, "您目前无任务，无法检查学生", Toast.LENGTH_SHORT).show();
//                                        } else {
//                                            Toast.makeText(TypeActivity.this, "当前学生不在所选任务内", Toast.LENGTH_SHORT).show();
//                                        }
//                                    }
//                                });
//                                return;
//                            }


                                }
                            } else if (type == 1) {
                                //邀请任务
                                String taskId = json.optString( "taskId" );
                                String userId = json.optString( "userId" );
                                String username = json.optString( "username" );
                                Intent intMain = new Intent( getApplicationContext(), ReceiveActivity.class );
                                Bundle bd = new Bundle();
                                bd.putString( "taskId", taskId );
                                bd.putString( "userId", userId );
                                bd.putString( "username", username );
                                intMain.putExtras( bd );
                                startActivity( intMain );
                            }

                        } catch (Exception e) {
                            // 捕获异常，如果要捕获Json数据异常，写catch(JSONException e)
                            e.printStackTrace();
                            String message = obj.getString( "message" );
                            ToastUtils.show( TypeActivity.this, message );
                            //如果JSONException e，打印出来就 Log.e(TAG, e.toString() + "");
                        }

                    }


                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        } );

    }

    private void showLogoutDialog() {
//        if (mQualifiedDialog == null) {
        mLogoutDialog = LogoutDialog.newInstance( false );
        mLogoutDialog.show( getSupportFragmentManager(), "mQualifiedDialog" );
        mLogoutDialog.setmListener( new LogoutDialog.OnItemClickListener() {

            @Override
            public void onConfirm() {
                startActivity( LoginActivity.class );
                mLogoutDialog.dismiss();
            }

            @Override
            public void onCancel() {
                mLogoutDialog.dismiss();
            }
        } );
    }


    private void compareFace(String filePath) {
        RestProxy.getInstance().compareFace( filePath, "", new Observer<CompareFaceResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(CompareFaceResponse compareFaceResponse) {
                try {
                    if (Float.parseFloat( compareFaceResponse.results.get( 0 ).confidence ) > 80) {
//                        getTaskWorker("1152059153087205378", compareFaceResponse.results.get(0).user_id);
                    } else {
                        Toast.makeText( TypeActivity.this, "识别失败", Toast.LENGTH_SHORT ).show();
                    }
                } catch (Exception e) {
                    Toast.makeText( TypeActivity.this, "识别失败", Toast.LENGTH_SHORT ).show();
                }
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
            }

            @Override
            public void onComplete() {

            }
        } );
    }


    @SuppressLint("NewApi")
    public String fileToBase64(String path) {
        String base64 = null;
        InputStream in = null;
        try {
            File file = new File( path );
            in = new FileInputStream( file );
            byte[] bytes = new byte[(int) file.length()];
            in.read( bytes );
            base64 = Base64.getEncoder().encodeToString( bytes );
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return base64;

    }

    @OnClick(R.id.tv_switch)
    void tv_switch() {
        Bundle bundle = new Bundle();
        bundle.putString( "title", "选择任务" );
        startActivityForResult( TaskListActivity.class, bundle, REQUEST_CODE_TASK );
    }


    /**
     * 获取任务列表
     *
     * @time 2020/6/10 14:25
     */
    private void getTaskList(boolean isLoading) {
        RestProxy.getInstance().getTaskList( 0,0 + "", "", "", "", "", "", new Observer<TaskListResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(TaskListResponse taskListResponse) {
                if (isLoading) {
                    if (taskListResponse.data.list.size() == 1) {
//                        tv_switch.setText("切换任务");
                        RestProxy.getInstance().isShowOther( taskListResponse.data.list.get( 0 ).taskId, new Observer<AxisResponse>() {
                            @Override
                            public void onSubscribe(Disposable d) {

                            }

                            @Override
                            public void onNext(AxisResponse axisResponse) {
                                LogUtil.e( "配置其他项" + axisResponse.data.other + "--" + axisResponse.data.Axis );
                                BaseApplication.isShowOther = axisResponse.data.other;
                                BaseApplication.isShowAxis = axisResponse.data.Axis;
                                icon_switch_mission.setVisibility( View.VISIBLE );
                                tv_mission_name.setText( taskListResponse.data.list.get( 0 ).taskOrgName );
                                currentSchoolName = taskListResponse.data.list.get( 0 ).taskOrgName;
                                currentTaskId = taskListResponse.data.list.get( 0 ).taskId;
                            }

                            @Override
                            public void onError(Throwable e) {
                                e.printStackTrace();
                                NetUtil.onError( e, mContext );
                            }

                            @Override
                            public void onComplete() {

                            }
                        } );

                    }
                } else {
                    if (taskListResponse.data.list.size() > 0) {
                        if (TextUtils.isEmpty( currentTaskId )) {
                            Bundle bundle = new Bundle();
                            bundle.putString( "title", "请先选择任务" );
                            startActivityForResult( TaskListActivity.class, REQUEST_CODE_TASK );
                            return;
                        }
                        startScan();
                    } else {
                        mScanDialog = ScanDialog.newInstance( "您当前无待完成任务，是否唤起扫一扫功能" );
                        mScanDialog.show( getSupportFragmentManager(), "mQualifiedDialog" );
                        mScanDialog.setmListener( new ScanDialog.OnItemClickListener() {

                            @Override
                            public void onConfirm() {
                                startScan();
                                mScanDialog.dismiss();
                            }

                            @Override
                            public void onCancel() {
                                if (TextUtils.isEmpty( currentTaskId )) {
                                    Bundle bundle = new Bundle();
                                    bundle.putString( "title", "请先选择任务" );
                                    startActivityForResult( TaskListActivity.class, bundle, REQUEST_CODE_TASK );
                                    return;
                                }
                                mScanDialog.dismiss();
                            }
                        } );
                    }
                }
            }

            @Override
            public void onError(Throwable e) {
                LogUtil.e( "异常111----", e );
                NetUtil.onError( e, TypeActivity.this );
                e.printStackTrace();
            }

            @Override
            public void onComplete() {
            }
        } );
    }

    private void startScan() {
        QrManager.getInstance().init( QrConfigUtil.getQrConfig() ).startScan( mContext, result -> {
            Log.e( "onScanSuccess---", result.getContent() );
            if (!UtilString.isEmpty( result.getContent() )) {
                try {
                    scanQRCode( result.getContent() );
//                    JSONObject obj = new JSONObject(content);
//                    getTaskWorker(obj.optString("taskId"), obj.optString("studentId"));
                } catch (Exception e) {
                    Toast.makeText( mContext, "二维码识别失败", Toast.LENGTH_SHORT ).show();
                }
            }
        } );
    }


    @Subscribe
    public void onMessageEvent(Logout logout) {
        finish();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(BlueTooth event) {
        LogUtil.e( "onMessageEvent" );
        if (event.type == 100) {
            ToastUtil.showToastCenter(mContext, event.output);
        }
    }

    private void showUpdateDialog(String url, int isUpdate) {
        mUpdateDialog = UpdateDialog.newInstance( isUpdate, false );
        mUpdateDialog.show( getSupportFragmentManager(), "mUpdateDialog" );
        mUpdateDialog.setmListener( new UpdateDialog.OnItemClickListener() {

            @Override
            public void onConfirm() {
                Intent intent = new Intent();
                intent.setData( Uri.parse( url ) );//Url 就是你要打开的网址
                intent.setAction( Intent.ACTION_VIEW );
                startActivity( intent ); //启动浏览器
                Objects.requireNonNull( mContext ).finish();
            }

            @Override
            public void onCancel() {

            }
        } );
    }

    private Bitmap getImageThumbnail(String imagePath) {
        Bitmap bitmap = null;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        // 获取这个图片的宽和高，注意此处的bitmap为null
        bitmap = BitmapFactory.decodeFile( imagePath, options );
        options.inJustDecodeBounds = false; // 设为 false
        // 计算缩放比
        int h = options.outHeight;
        int w = options.outWidth;
        int beWidth = w / 500;
        int beHeight = h / 500;
        int be = 1;
        if (beWidth < beHeight) {
            be = beWidth;
        } else {
            be = beHeight;
        }
        if (be <= 0) {

            be = 1;
        }
        options.inSampleSize = be;
        // 重新读入图片，读取缩放后的bitmap，注意这次要把options.inJustDecodeBounds 设为 false
        bitmap = BitmapFactory.decodeFile( imagePath, options );
        // 利用ThumbnailUtils来创建缩略图，这里要指定要缩放哪个Bitmap对象
        bitmap = ThumbnailUtils.extractThumbnail( bitmap, 500, 500,
                ThumbnailUtils.OPTIONS_RECYCLE_INPUT );
        return bitmap;
    }


    private void checkPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            List<String> permissions = new ArrayList<>();
            if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission( this, Manifest.permission.CAMERA )) {
                permissions.add( Manifest.permission.CAMERA );
            }
            if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission( this, Manifest.permission.WRITE_EXTERNAL_STORAGE )) {
                permissions.add( Manifest.permission.WRITE_EXTERNAL_STORAGE );
            }
            if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission( this, Manifest.permission.READ_EXTERNAL_STORAGE )) {
                permissions.add( Manifest.permission.READ_EXTERNAL_STORAGE );
            }
            if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission( this, Manifest.permission.RECORD_AUDIO )) {
                permissions.add( Manifest.permission.RECORD_AUDIO );
            }
            if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission( this, Manifest.permission.ACCESS_COARSE_LOCATION )) {
                permissions.add( Manifest.permission.ACCESS_COARSE_LOCATION );
            }
            if (permissions.size() != 0) {
                ActivityCompat.requestPermissions( this, permissions.toArray( new String[0] ), 100 );
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister( this );

    }
}
